﻿using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using ImageEffects;
using LogSystem;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Core.Timeline;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class AddTimelineInstanceNode : LatentActionNodeBase
    {
        public override bool allowRoutineQueueing { get { return false; } }

        private TimelineConstructor _timelineConstructor;
        private bool _loaded = false;

        public IEnumerator Invoke(string resPath)
        {
            TimelineConstructorMgr.GetInstance("TimelineConstructorMgr")?.AddTimelineInstance(resPath,(constructor =>
            {
                _timelineConstructor = constructor;
                _loaded = true;
            }));

            while (!_loaded)
            {
                yield return new WaitForOneFrame();
            }
        }
        
        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            var p1 = node.AddValueInput<string>("resPath");
            
            node.AddFlowInput("In", (f) => { Begin(Invoke(p1.value), f); });
            
            node.AddValueOutput<TimelineConstructor>("TimelineConstructor", () => _timelineConstructor);
        }

        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (_timelineConstructor)
            {
                TimelineConstructorMgr.GetInstance("TimelineConstructorMgr")?.RemoveConstructor(_timelineConstructor);
                TimelineConstructorMgr.GetInstance("TimelineConstructorMgr")?.DestroyConstructor(_timelineConstructor);
                _timelineConstructor = null;
            }
        }
        
    }
}